<?php

namespace app\admin\model;

use think\Model;

class Login extends Model
{
    protected $name = 'users';
    // 隐藏敏感字段（避免返回密码等）
    protected $hidden = ['password', 'password_confirm', 'create_time', 'update_time',];

    /**
     * 根据用户名查找用户
     */
    public static function findByUsername(string $username)
    {
        return self::where('username', $username)->find();
    }

    /**
     * 根据ID查找用户
     */
    public static function findById(int $id)
    {
        return self::find($id);
    }

    /**
     * 验证密码
     */
    public function verifyPassword(string $password)
    {
        return password_verify($password, $this->password);
    }

    /**
     * 更新登录时间
     */
    public function updateLoginTime()
    {
        $this->login_time = time();
        return $this->save();
    }

    /**
     * 更新用户信息
     */
    public function updateUserInfo(array $data)
    {
        if (isset($data['username'])) {
            $this->username = trim($data['username']);
        }
        if (isset($data['email'])) {
            $this->email = trim($data['email']);
        }
        if (isset($data['phone'])) {
            $this->phone = trim($data['phone']);
        }
        if (isset($data['avatar'])) {
            $this->avatar = trim((string)$data['avatar']);
        }
        if (!empty($data['password'])) {
            $this->password = password_hash(trim($data['password']), PASSWORD_DEFAULT);
        }

        return $this->save();
    }

    /**
     * 检查用户名是否存在（排除指定ID）
     */
    public static function checkUsernameExists(string $username, int $excludeId = 0)
    {
        $query = self::where('username', trim($username));
        if ($excludeId > 0) {
            $query->where('id', '<>', $excludeId);
        }
        return $query->find();
    }

    /**
     * 检查邮箱是否存在（排除指定ID）
     */
    public static function checkEmailExists(string $email, int $excludeId = 0)
    {
        $query = self::where('email', trim($email));
        if ($excludeId > 0) {
            $query->where('id', '<>', $excludeId);
        }
        return $query->find();
    }

    /**
     * 检查手机号是否存在（排除指定ID）
     */
    public static function checkPhoneExists(string $phone, int $excludeId = 0)
    {
        $query = self::where('phone', trim($phone));
        if ($excludeId > 0) {
            $query->where('id', '<>', $excludeId);
        }
        return $query->find();
    }
}